package utils

import (
	"encoding/binary"
	"fmt"
	"math"
	"strconv"
	"unsafe"
)

func main() {
	bs := Float32ToByte(30)
	//
	fmt.Printf("%2x\r\n", bs)
	//fbytes := [4]byte{0x41,0xF7,0x3F,0x7E};  x
	fbytes := [4]byte{0x97, 0xEB, 0xEB, 0x41}
	f := ByteToFloat32(fbytes[:])
	fmt.Printf("%f\n", f)
	fmt.Printf("%b\r\n", IsLittleEndian())
	fmt.Printf("%2x", Float32ToByte(30.9)[:])

}
func Float32ToByte(float float32) []byte {
	bits := math.Float32bits(float)
	bytes := make([]byte, 4)
	binary.LittleEndian.PutUint32(bytes, bits)

	return bytes
}
func IsLittleEndian() bool {
	var i int32 = 0x01020304
	u := unsafe.Pointer(&i)
	pb := (*byte)(u)
	b := *pb
	return (b == 0x04)
}
func ByteToFloat32(bytes []byte) float32 {
	bits := binary.LittleEndian.Uint32(bytes)

	return math.Float32frombits(bits)
}

func Float64ToByte(float float64) []byte {
	bits := math.Float64bits(float)
	bytes := make([]byte, 8)
	binary.LittleEndian.PutUint64(bytes, bits)

	return bytes
}

func ByteToFloat64(bytes []byte) float64 {
	bits := binary.LittleEndian.Uint64(bytes)
	return math.Float64frombits(bits)
}

/*
四舍五入转换浮点数64位
*/
func RoundFloat64(value float64, precision int) float64 {
	fmtstr := fmt.Sprintf("%%.%df", precision)
	val, _ := strconv.ParseFloat(fmt.Sprintf(fmtstr, value), 64)
	return val
}

/*
四舍五入转换浮点数32位
*/
func RoundFloat32(val float32, precision int) float32 {
	return float32(RoundFloat64(float64(val), precision))
}
